package com.yzt.minemodule.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.config.AppConfigCacheManager;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.user.PersonalRefresh;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.mine.FileBean;
import com.yzt.zhuju.network.entity.user.PersonEditLayoutEntry;
import com.yzt.zhuju.network.entity.user.PersonalDetail;
import com.yzt.zhuju.upload.UploadFileManager;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.zhuju.utils.CountryJsonUtil;
import com.yzt.zhuju.widget.pickview.TimePickerViewManager;
import com.yzt.zhuju.widget.pickview.WhellPickerViewManager;
import com.yzt.minemodule.R;
import com.yzt.minemodule.adapter.MatchProfileAdapter;
import com.yzt.p_base.utils.DateUtils;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.plugin_widget.RoundImageView;
//import com.wildma.pictureselector.PictureSelector;
//import com.yanzhenjie.album.Album;
//import com.yanzhenjie.album.AlbumFile;
//import com.yanzhenjie.album.api.widget.Widget;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * author : bob
 * date   : 2023/2/22
 * desc   :
 */
@Deprecated
@Route(path = RouterUser.ACTIVITY_MATCH_PROFILE)
public class MatchProfileActivity extends BaseActivity {

    private final int RESULT_CODE_NICKNAME = 100;

    private final int RESULT_CODE_AUTOGRAPH = 101;

    /**
     * 国家列表
     */
    private List<String> stringNational;

    @Autowired
    String mUserId;

    @Autowired
    boolean isShowGuide;

    /**
     * 内容设配器
     */
    private MatchProfileAdapter matchProfileAdapter;

    private PersonalDetail mPersonalDetail;

    // 添加按钮
    private ImageView imgAddVideo;

    // 视频容器
    private FrameLayout fLVideoDetail;

    private RoundImageView imgVideo;

    @Override
    public int getLayoutId() {
        return R.layout.activity_match_profile;
    }

    @Override
    public void installViews() {
        setFullScreen(true);

        if (TextUtils.isEmpty(mUserId)) {
            mUserId = RXingUtils.getUserId();
        }

        imgAddVideo = findViewById(R.id.img_add_video);

        fLVideoDetail = findViewById(R.id.fl_video_detail);

        imgVideo = findViewById(R.id.img_video);

        findViewById(R.id.left_layout).setOnClickListener(this);

        findViewById(R.id.img_add_video).setOnClickListener(this);

        findViewById(R.id.img_del).setOnClickListener(this);

        findViewById(R.id.img_play).setOnClickListener(this);

        // 用户基础资料
        initUserInfo();

        // 获取用户信息
        getHttpData();

        stringNational = CountryJsonUtil.getCountryJsonList(this);

        AppConfigCacheManager.getInstance().getNationalList();

        if (isShowGuide) {
            uploadAvatar();
        }
    }

    /**
     * 基础资料监听
     */
    private void initUserInfo() {

        RecyclerView recycler = findViewById(R.id.item_layout_rv);
        matchProfileAdapter = new MatchProfileAdapter();
        recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        recycler.setAdapter(matchProfileAdapter);

        // 基本资料
        matchProfileAdapter.setOnItemClickListener((adapter, view, position) -> {
            PersonEditLayoutEntry itemLayoutEntry = (PersonEditLayoutEntry) adapter.getData().get(position);
            switch (itemLayoutEntry.getId()) {
                case PersonEditLayoutEntry.TYPE_NICK_NAME:
                    // 昵称
                    EditInfoActivity.start(mActivity, EditInfoActivity.TYPE_NICKNAME, itemLayoutEntry.getContent(), RESULT_CODE_NICKNAME);
                    break;
                case PersonEditLayoutEntry.TYPE_AGE:
                    // 年龄
                    String content = itemLayoutEntry.getContent();
                    int year = 1990;
                    int month = 0;
                    int day = 1;
                    boolean isHappenCatch = false;
                    if (!TextUtils.isEmpty(content)) {
                        String[] split = content.split(mActivity.getString(R.string.str_space2));
                        if (split.length > 2) {
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                            try {
                                int[] yearMonthDay = DateUtils.getYearMonthDay(sf.parse(split[2]));
                                year = yearMonthDay[0];
                                month = yearMonthDay[1];
                                day = yearMonthDay[2];
                            } catch (ParseException e) {
                                e.printStackTrace();
                                isHappenCatch = true;
                            }
                        } else {
                            isHappenCatch = true;
                        }
                    } else {
                        isHappenCatch = true;

                    }
                    if (isHappenCatch) {
                        //发生了异常 说明 没有选择过年龄
                        Calendar defaultDate = Calendar.getInstance();
                        year = defaultDate.get(Calendar.YEAR) - 25;
                        month = defaultDate.get(Calendar.MONTH);
                        day = defaultDate.get(Calendar.DAY_OF_MONTH);
                    }

                    //时间选择
                    TimePickerViewManager mTimeManager = TimePickerViewManager.getInstance(this);
                    Calendar selectDate = Calendar.getInstance();
                    try {
                        selectDate.set(year, month, day);
                    } catch (Exception e) {
                        e.printStackTrace(); //防止设置时发生平年 闰年问题
                        selectDate.set(year, month, day > 1 ? day - 1 : day);
                    }
                    mTimeManager.setSelectCalendar(selectDate);

                    int endyear = 2002;
                    int endMonth = 1;
                    int endDay = 1;

                    int startYear = 1921;
                    try {
                        String date = DateUtils.formatTime(DateUtils.getNowTimeStamp(), DateUtils.FORMAT);
                        String[] split = date.split("-");
                        endyear = Integer.parseInt(split[0]);
                        startYear = endyear - 99;
                        endyear = endyear - 18;
                        endMonth = Integer.parseInt(split[1]);
                        endDay = Integer.parseInt(split[2]);
                    } catch (Exception ignored) {

                    }
                    Calendar startDate = Calendar.getInstance();
                    startDate.set(startYear, 0, 1);
                    Calendar endDate = Calendar.getInstance();
                    endDate.set(endyear, endMonth - 1, endDay);
                    mTimeManager.initTimePickerView(mActivity, startDate, endDate, date -> {
                        String dateTime = DateUtils.getDateTime(date, "yyyy-MM-dd");
                        JSONObject json = new JSONObject();
                        json.put("birthday", dateTime.split("-")[2]);
                        json.put("birthmonth", dateTime.split("-")[1]);
                        json.put("birthyear", dateTime.split("-")[0]);
                        BizLayer.getInstance().getAccountModule().editUserInfo(json, new AresSubscriber<Object>() {
                            @Override
                            protected void onSuccess(Object response) {
                                ToastUtil.showMessage(getString(R.string.edit_success));
                                matchProfileAdapter.setData(position,
                                        new PersonEditLayoutEntry(itemLayoutEntry.getId(), mActivity.getString(R.string.str_age_star),
                                                mActivity.getString(R.string.str_select),
                                                mActivity.getString(R.string.mine_age_star,
                                                        String.valueOf(DateUtils.getAge(date, new Date())),
                                                        DateUtils.getHoroscope(date, MatchProfileActivity.this),
                                                        "")));// dateTime
                            }
                        });

                    });
                    mTimeManager.showTimePicmkerView();
                    break;

                case PersonEditLayoutEntry.TYPE_ADDRESS:
                    // 所在地
                    if (stringNational == null) {
                        return;
                    }
                    stringNational = CountryJsonUtil.getCountryJsonList(this);
                    WhellPickerViewManager whellPickerViewManager = WhellPickerViewManager.getInstance(mActivity).builder(stringNational);
                    whellPickerViewManager.setDefault(address);
                    whellPickerViewManager.showPickerView();
                    whellPickerViewManager.setOnCallOptionsListener(new WhellPickerViewManager.OnCallOptionsListener() {
                        @Override
                        public void callBackInfo(String sw1, String sw2) {
                            BizLayer.getInstance().getAccountModule().editUserInfo("residecity", sw1, new AresSubscriber<Object>() {
                                @Override
                                protected void onSuccess(Object response) {
                                    ToastUtil.showMessage(getString(R.string.edit_success));
                                    address = sw1;
                                    matchProfileAdapter.setData(position, new PersonEditLayoutEntry(itemLayoutEntry.getId(),
                                            mActivity.getString(R.string.str_address),
                                            mActivity.getString(R.string.str_select),
                                            address));
                                }
                            });
                        }
                    });
                    break;
//                case PersonEditLayoutEntry.TYPE_BIO:
//                    // 签名
//                    EditInfoActivity.start(mActivity, EditInfoActivity.TYPE_AUTOGRAPH, itemLayoutEntry.getContent(), RESULT_CODE_AUTOGRAPH);
//                    break;
                default:
                    break;
            }
        });
    }

    /**
     * 上传逻辑
     */
    private void uploadAvatar() {
//        PictureSelector.create(mActivity, PictureSelector.SELECT_REQUEST_CODE)
//                .selectPicture(true, DisplayUtils.dp2px(300), DisplayUtils.dp2px(300), 1, 1);
    }

    public void getHttpData() {
        BizLayer.getInstance().getAccountModule().getUserFullInfo(mUserId, new AresSubscriber<PersonalDetail>() {
            @Override
            protected void onSuccess(PersonalDetail personalDetail) {
                mPersonalDetail = personalDetail;
                initData();
            }
        });
    }


    private String address = "";

    /**
     * 加载用户信息
     */
    public void initData() {
//        List<PersonEditLayoutEntry> mItemList = new ArrayList<>();
//        PersonalDetailBasic basic = mPersonalDetail.getBasic();
//        address = basic.getAddress();
//        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_NICK_NAME, mActivity.getString(R.string.str_nickname), basic.getUserNameStatus() != 1, mActivity.getString(R.string.str_input), basic.getUserName()));
//        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_GENDER, mActivity.getString(R.string.str_gender), mActivity.getString(R.string.str_select), RXingUtils.getGenderStr(mActivity, basic.getGender()), true));
//
//        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_AGE, mActivity.getString(R.string.str_age_star), mActivity.getString(R.string.str_select),
//                mActivity.getString(R.string.mine_age_star,
//                        String.valueOf(basic.getAge()),
//                        basic.getHoroscope(),
//                        "")));
//        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_ADDRESS, mActivity.getString(R.string.str_address), mActivity.getString(R.string.str_select), address));
//        mItemList.add(new PersonEditLayoutEntry(PersonEditLayoutEntry.TYPE_BIO, mActivity.getString(R.string.str_autograph), basic.getSloganStatus() != 1, mActivity.getString(R.string.str_input), basic.getSlogan()));
//        matchProfileAdapter.setList(mItemList);
//
//        if (basic.getVideoUrl() != null && !basic.getVideoUrl().equals("")) {
//            fLVideoDetail.setVisibility(View.VISIBLE);
//            imgAddVideo.setVisibility(View.GONE);
//            Glide.with(this)
//                    .load(basic.getVideoCover())
//                    .error(R.mipmap.icon_placeholder_long)
//                    .placeholder(R.mipmap.icon_placeholder_long)
//                    .into(imgVideo);
//        } else {
//            fLVideoDetail.setVisibility(View.GONE);
//            imgAddVideo.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.left_layout) {
            // 页面关闭
            finish();
        }
        if (view.getId() == R.id.img_play) {
            // 播放视频
          //  String path = mPersonalDetail.getBasic().getVideoUrl();
            //VideoPlayActivity.startActivity(mActivity, "2", path);
           // RouterMine.VideoPlayActivity("2", path);
        }

        if (view.getId() == R.id.img_del) {
            // 删除视频
            AppDialogUtil.showNoTitleDialog(this, getString(R.string.del_video), getString(R.string.cancel), getString(R.string.confirm), new AppDialogUtil.DialogClickInterface() {

                @Override
                public void onCancelClick() {

                }

                @Override
                public void onSureClick() {
                    fLVideoDetail.setVisibility(View.GONE);
                    imgAddVideo.setVisibility(View.VISIBLE);
                    delVideo();
                }
            });
        }

        if (view.getId() == R.id.img_add_video) {
            // 添加视频
//            Album.video(this)
//                    .multipleChoice()
//                    .columnCount(3)
//                    .selectCount(1)
//                    .camera(false)
//                    // .checkedList(mAlbumFiles)
//                    .widget(Widget.newDarkBuilder(this)
//                            .title("Select Video")
//                            .build()
//                    )
//                    .onResult(result -> {
//                        mVideoFiles = result;
//                        if (mVideoFiles.size() > 0) {
//                            AlbumFile file = mVideoFiles.get(0);
//                            Album.getAlbumConfig().getAlbumLoader().load(imgVideo, file);
//                            fLVideoDetail.setVisibility(View.VISIBLE);
//                            imgAddVideo.setVisibility(View.GONE);
//                            uploadVideo();
//                        }
//                    }).onCancel(result -> {
//
//                    }).start();
        }
    }

   // private ArrayList<AlbumFile> mVideoFiles;

    /**
     * 上传视频
     */
//    private void uploadVideo() {
//
//        if (mVideoFiles != null && !mVideoFiles.isEmpty()) {
//
//            String picturePath = mVideoFiles.get(0).getPath();
//            showMProgress();
//
//            UploadFileManager.getInstance().uploadVideo(picturePath, new UploadFileManager.UploadCallback() {
//                @Override
//                public void uploadSuccess(FileBean fileBean) {
//                    // 获取用户信息
//                    getHttpData();
//                    closeProgress();
//                }
//
//                @Override
//                public void uploadFail(int code, String info) {
//                    closeProgress();
//                }
//            });
//        }
//    }

    /**
     * 删除视频模块
     */
    public void delVideo() {
        BizLayer.getInstance().getAccountModule().delVideo(new AresSubscriber<Object>() {
            @Override
            protected void onSuccess(Object response) {
                fLVideoDetail.setVisibility(View.GONE);
                imgAddVideo.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE_NICKNAME:
                case RESULT_CODE_AUTOGRAPH:
                    getHttpData();
                    break;
                default:
                    break;
            }
        }

//        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
//            if (data != null) {
//                String picturePath = ModulePictureSelectUtils.getPicturePath(data);
//                showMProgress();
//                UploadFileManager.getInstance().upload(picturePath, 0, new UploadFileManager.UploadCallback() {
//                    @Override
//                    public void uploadSuccess(FileBean fileBean) {
//
//                    }
//
//                    @Override
//                    public void uploadFail(int code, String info) {
//                        closeProgress();
//                    }
//                });
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().post(new PersonalRefresh());
    }
}
